package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.StudentAnswerDTO;
import org.csu.onlineedubackend.dto.StudentAnswerStatsDTO;
import org.csu.onlineedubackend.entity.StudentAnswer;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.StudentAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/student-answer")
public class StudentAnswerController {
    
    @Autowired
    private StudentAnswerService studentAnswerService;

    /**
     * 學生提交作業答案
     */
    @PostMapping("/submit")
    public CommonResponse<StudentAnswerDTO> submitAnswer(@RequestBody StudentAnswerDTO answerDTO) {
        try {
            StudentAnswer answer = new StudentAnswer();
            BeanUtils.copyProperties(answerDTO, answer);
            
            // 設置作答時間
            answer.setAnsweredAt(new java.util.Date());
            
            StudentAnswer saved = studentAnswerService.submitAnswer(answer);
            
            StudentAnswerDTO resultDTO = new StudentAnswerDTO();
            BeanUtils.copyProperties(saved, resultDTO);
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "作業提交成功", 
                resultDTO
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "作業提交失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 更新學生作業答案
     */
    @PutMapping("/update")
    public CommonResponse<StudentAnswerDTO> updateAnswer(@RequestBody StudentAnswerDTO answerDTO) {
        try {
            // 不再需要检查ID，因为我们总是创建新记录
            StudentAnswer answer = new StudentAnswer();
            BeanUtils.copyProperties(answerDTO, answer);
            
            // 清除ID，确保创建新记录
            answer.setId(null);
            
            // 设置作答时间
            answer.setAnsweredAt(new java.util.Date());
            
            // 提交新答案
            StudentAnswer saved = studentAnswerService.submitAnswer(answer);
            
            StudentAnswerDTO resultDTO = new StudentAnswerDTO();
            BeanUtils.copyProperties(saved, resultDTO);
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "作業提交成功", 
                resultDTO
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "作業提交失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 根據題目ID查詢所有學生答案
     */
    @GetMapping("/question/{questionId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByQuestion(@PathVariable Integer questionId) {
        try {
            List<StudentAnswer> answers = studentAnswerService.getAnswersByQuestionId(questionId);
            List<StudentAnswerDTO> answerDTOs = answers.stream()
                    .map(answer -> {
                        StudentAnswerDTO dto = new StudentAnswerDTO();
                        BeanUtils.copyProperties(answer, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTOs
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 根據學生ID查詢所有答案
     */
    @GetMapping("/student/{studentId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByStudent(@PathVariable Integer studentId) {
        try {
            List<StudentAnswer> answers = studentAnswerService.getAnswersByStudentId(studentId);
            List<StudentAnswerDTO> answerDTOs = answers.stream()
                    .map(answer -> {
                        StudentAnswerDTO dto = new StudentAnswerDTO();
                        BeanUtils.copyProperties(answer, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTOs
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 根據題目ID和學生ID查詢特定答案
     */
    @GetMapping("/{questionId}/{studentId}")
    public CommonResponse<StudentAnswerDTO> getAnswerByQuestionAndStudent(
            @PathVariable Integer questionId, 
            @PathVariable Integer studentId) {
        try {
            StudentAnswer answer = studentAnswerService.getAnswerByQuestionAndStudent(questionId, studentId);
            
            if (answer == null) {
                return CommonResponse.createForError(
                    ResponseCode.ERROR.getCode(), 
                    "未找到該學生的答案"
                );
            }
            
            StudentAnswerDTO answerDTO = new StudentAnswerDTO();
            BeanUtils.copyProperties(answer, answerDTO);
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTO
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 老師批改作業（設置是否正確）
     */
    @PostMapping("/mark")
    public CommonResponse<String> markAnswer(
            @RequestParam Integer answerId, 
            @RequestParam boolean isCorrect) {
        try {
            boolean success = studentAnswerService.markAnswer(answerId, isCorrect);
            
            if (success) {
                return CommonResponse.createForSuccess(
                    ResponseCode.SUCCESS.getCode(), 
                    "批改成功"
                );
            } else {
                return CommonResponse.createForError(
                    ResponseCode.ERROR.getCode(), 
                    "批改失敗，可能答案不存在"
                );
            }
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "批改失敗: " + e.getMessage()
            );
        }
    }
    
    /**
     * 老師給作業打分
     */
    @PostMapping("/score")
    public CommonResponse<String> scoreAnswer(
            @RequestParam Integer answerId, 
            @RequestParam Double score) {
        try {
            boolean success = studentAnswerService.scoreAnswer(answerId, score);
            
            if (success) {
                return CommonResponse.createForSuccess(
                    ResponseCode.SUCCESS.getCode(), 
                    "评分成功"
                );
            } else {
                return CommonResponse.createForError(
                    ResponseCode.ERROR.getCode(), 
                    "评分失败，可能答案不存在"
                );
            }
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "评分失败: " + e.getMessage()
            );
        }
    }

    /**
     * 刪除學生答案
     */
    @DeleteMapping("/{answerId}")
    public CommonResponse<String> deleteAnswer(@PathVariable Integer answerId) {
        try {
            // 先檢查答案是否存在
            StudentAnswer answer = studentAnswerService.getById(answerId);
            if (answer == null) {
                return CommonResponse.createForError(
                    ResponseCode.ERROR.getCode(), 
                    "答案不存在"
                );
            }
            
            boolean deleted = studentAnswerService.deleteAnswer(answerId);
            
            if (deleted) {
                return CommonResponse.createForSuccess(
                    ResponseCode.SUCCESS.getCode(), 
                    "答案刪除成功"
                );
            } else {
                return CommonResponse.createForError(
                    ResponseCode.ERROR.getCode(), 
                    "答案刪除失敗"
                );
            }
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "答案刪除失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 根據課程ID查詢所有學生答案
     */
    @GetMapping("/course/{courseId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByCourse(@PathVariable Integer courseId) {
        try {
            List<StudentAnswer> answers = studentAnswerService.getAnswersByCourseId(courseId);
            List<StudentAnswerDTO> answerDTOs = answers.stream()
                    .map(answer -> {
                        StudentAnswerDTO dto = new StudentAnswerDTO();
                        BeanUtils.copyProperties(answer, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTOs
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 根據學生ID和課程ID查詢答案
     */
    @GetMapping("/student/{studentId}/course/{courseId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByStudentAndCourse(
            @PathVariable Integer studentId, 
            @PathVariable Integer courseId) {
        try {
            List<StudentAnswer> answers = studentAnswerService.getAnswersByStudentAndCourse(studentId, courseId);
            List<StudentAnswerDTO> answerDTOs = answers.stream()
                    .map(answer -> {
                        StudentAnswerDTO dto = new StudentAnswerDTO();
                        BeanUtils.copyProperties(answer, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTOs
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 獲取學生作業統計信息
     */
    @GetMapping("/stats/student/{studentId}")
    public CommonResponse<StudentAnswerStatsDTO> getStudentAnswerStats(@PathVariable Integer studentId) {
        try {
            // 這裡需要實現統計邏輯
            // 暫時返回空對象，需要擴展 Service 來支持統計功能
            StudentAnswerStatsDTO stats = new StudentAnswerStatsDTO();
            stats.setStudentId(studentId);
            stats.setTotalQuestions(0);
            stats.setAnsweredQuestions(0);
            stats.setCorrectAnswers(0);
            stats.setCorrectRate(0.0);
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                stats
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 獲取課程作業統計信息
     */
    @GetMapping("/stats/course/{courseId}")
    public CommonResponse<List<StudentAnswerStatsDTO>> getCourseAnswerStats(@PathVariable Integer courseId) {
        try {
            // 這裡需要實現統計邏輯
            // 暫時返回空列表，需要擴展 Service 來支持統計功能
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                new java.util.ArrayList<>()
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 獲取學生某題的所有歷史作業答案
     */
    @GetMapping("/history/{questionId}/{studentId}")
    public CommonResponse<List<StudentAnswerDTO>> getHistoryAnswersByQuestionAndStudent(
            @PathVariable Integer questionId, 
            @PathVariable Integer studentId) {
        try {
            List<StudentAnswer> answers = studentAnswerService.getHistoryAnswersByQuestionAndStudent(questionId, studentId);
            
            if (answers.isEmpty()) {
                return CommonResponse.createForSuccess(
                    ResponseCode.SUCCESS.getCode(), 
                    "該學生尚未提交作業",
                    new java.util.ArrayList<>()
                );
            }
            
            List<StudentAnswerDTO> answerDTOs = answers.stream()
                    .map(answer -> {
                        StudentAnswerDTO dto = new StudentAnswerDTO();
                        BeanUtils.copyProperties(answer, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(), 
                "查詢成功", 
                answerDTOs
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(), 
                "查詢失敗: " + e.getMessage()
            );
        }
    }

    /**
     * 獲取學生未完成的作業
     */
    @GetMapping("/pending-assignments")
    public CommonResponse<List<Object>> getPendingAssignments(@RequestParam("userId") Long userId) {
        try {
            List<Object> pendingAssignments = studentAnswerService.getPendingAssignments(userId);
            return CommonResponse.createForSuccess(
                ResponseCode.SUCCESS.getCode(),
                "查詢成功",
                pendingAssignments
            );
        } catch (Exception e) {
            return CommonResponse.createForError(
                ResponseCode.ERROR.getCode(),
                "查詢失敗: " + e.getMessage()
            );
        }
    }
} 